package thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyFooBar {
    private int n;
    private final Lock lock = new ReentrantLock();
    private final Condition fooCon = lock.newCondition();
    private final Condition barCon = lock.newCondition();
    private volatile boolean flag = false;

    public MyFooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        lock.lock();
        try {
            for (int i = 0; i < n; i++) {
                if (flag) {
                    fooCon.await();
                }
                printFoo.run();
                flag = true;
                barCon.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        lock.lock();
        try {
            for (int i = 0; i < n; i++) {
                if (!flag) {
                    barCon.await();
                }
                printBar.run();
                flag = false;
                fooCon.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}

public class FooBar_1115 {

    public static void main(String[] args) {
        test1();
    }

    private static void test1() {
        MyFooBar myFooBar = new MyFooBar(4);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    myFooBar.bar(new Runnable() {
                        @Override
                        public void run() {
                            System.out.print("bar");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    myFooBar.foo(new Runnable() {
                        @Override
                        public void run() {
                            System.out.print("foo");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

